import { _parkInfo, _discountsInfo, _pay } from '../../common/parking'
import { formatDate, formatNumber } from '../../utils/util'
const computedBehavior = require('miniprogram-computed')
const app = getApp()
Component({
  behaviors: [computedBehavior],
  data: {
    openid: '',
    cardnum: '',
    info: null,
    vipDiscounts: null,
    discounts: [],
    choosedDiscounts: [],
    lengthLimit: Infinity,
    discountsTimes: 0,
    chooseShow: false,
    price: 0
  },
  computed: {
    showenCard() {
      let num = this.data.cardnum.split('')
      num.splice(2, 0, ' ')
      return num
    },
    addBar() {
      return /iphone\sx/i.test(app.globalData.phone.toLowerCase())
    },
    originFee () {
      let fee = '0.00'
      if (this.data.info) {
        fee = formatNumber(this.data.info.chargeMoney / 100, 2)
      }
      return fee
    },
    finalFee() {
      const price = this.data.price
      const originCost = this.data.info ? this.data.info.chargeMoney / 100 : 0
      const vipMinus = this.data.vipDiscounts ? this.data.vipDiscounts.hours * price : 0
      const discountsMinus = this.data.discountsTimes * price
      let res = originCost - vipMinus - discountsMinus
      res = res > 0 ? res : 0
      let fee = formatNumber(res, 2)
      return fee
    },
    parkedTime() {
      let time = ''
      if (this.data.info) {
        const total = this.data.info.parkingSeconds
        let second = total % 60
        let minutes = ((total - second) / 60) % 60 + ''
        minutes = ('00' + minutes).substr(minutes.length)
        let hours = Math.floor(Math.floor((total - second) / 60) / 60)
        second += ''
        second = ('00' + second).substr(second.length)
        hours += ''
        hours = ('00' + hours).substr(hours.length)
        time = `${hours}:${minutes}:${second}`
      }
      return time
    },
    enterTime() {
      return this.data.info ? this.data.info.inTime : ''
    },
    finalDiscounts () {
      let final = 0
      if (this.data.vipDiscounts) {
        final += this.data.vipDiscounts.hours
      }
      // return final + this.data.discountsTimes
      return Math.min(final + this.data.discountsTimes, this.data.lengthLimit)
    }
  },
  methods: {
    showChoose () {
      this.setData({
        chooseShow: true
      })
    },
    hideChoose() {
      this.setData({
        chooseShow: false
      })
    },
    confirmChoose () {
      this.hideChoose()
    },
    chooseHandler (e) {
      let choosed = e.detail.value
      let discounts = this.data.discounts
      let discountsTimes = 0
      let lengthLimit = this.data.lengthLimit
      const vipHours = this.data.vipDiscounts ? this.data.vipDiscounts.hours : 0
      let choosedDiscounts = discounts.filter((item, index) => {
        if (choosed.includes(index + '')) {
          item.checked = true
          discountsTimes += item.hours
          if (discountsTimes + vipHours > lengthLimit) {
            app.toast(`抵扣总时长不能超过${lengthLimit}小时`)
            discountsTimes = lengthLimit - vipHours
          }
          return item
        } else {
          item.checked = false
        }
      })
      this.setData({
        choosedDiscounts,
        discountsTimes,
        discounts
      })
    },
    totalQuery () {
      let cardnum = this.data.cardnum
      let openid = this.data.openid
      app.loading('加载中')
      Promise.all([
        _parkInfo(
          openid,
          cardnum
        ),
        _discountsInfo(
          openid,
          cardnum
        )
      ]).then(res => {
        wx.hideLoading()
        let info = res[0].data.Data
        const total = info ? info.parkingSeconds : 0
        let second = total % 60
        let minutes = ((total - second) / 60) % 60
        let hours = Math.floor(Math.floor((total - second) / 60) / 60)
        let myHours = hours + (minutes > 0 ? 1 : 0)
        if (!res[0].data.IsSuccess) {
          wx.showModal({
            title: '对不起',
            content: res[0].data.Msg,
            showCancel: false,
            success: r => {
              wx.navigateBack({
                fail: () => {
                  wx.redirectTo({
                    url: './query'
                  })
                }
              })
            }
          })
          return
        }
        let vipDiscounts = res[1].data.Data.VipTicket[0] || null
        if (vipDiscounts) {
          vipDiscounts.endtime = vipDiscounts.endtime.replace('T', ' ')
        }
        let discounts = res[1].data.Data.Tickets
        let lengthLimit = res[1].data.Data.MaxHours
        lengthLimit = Math.min(myHours, lengthLimit)
        let price = res[1].data.Data.Price
        this.setData({
          info,
          vipDiscounts,
          discounts,
          lengthLimit,
          price
        })
      }).catch(err => {
        console.log(err)
        wx.hideLoading()
        wx.showModal({
          title: '对不起',
          content: err||'请求错误，请稍后再试'
        })
      })
    },
    pay () {
      const cardnum = this.data.cardnum
      const openid = this.data.openid
      const paytime = this.data.info.payTime
      const tickets = this.data.choosedDiscounts.map(item => item.code).join(',')
      const vipticket = this.data.vipDiscounts ? this.data.vipDiscounts.code : ''
      app.loading('加载中')
      _pay(openid, cardnum, paytime, tickets, vipticket).then(res => {
        console.log(res)
        wx.hideLoading()
        if (res.data.IsSuccess) {
          console.log(res.data.Data)
          let {
            timeStamp,
            nonceStr,
            paySign
          } = res.data.Data
          let _package = res.data.Data.package
          wx.requestPayment({
            timeStamp,
            nonceStr,
            package: _package,
            signType: 'MD5',
            paySign,
            success: pr => {
              wx.showModal({
                title: '温馨提示',
                content: '支付成功',
                showCancel: false,
                success: r => {
                  wx.navigateTo({
                    url: './record'
                  })
                }
              })
            },
            fail: pe => {
              wx.showModal({
                title: '对不起',
                content: '支付失败',
                showCancel: false,
                success: r => {
                }
              })
            }
          })
        } else {
          wx.showModal({
            title: '对不起',
            content: res.data.Msg,
            showCancel: false
          })
        }
      }).catch(err => {
        console.log(err)
        wx.hideLoading()
        wx.showModal({
          title: '对不起',
          content: JSON.stringify(err) || '请求失败，请稍后再试',
          showCancel: false
        })
      })
    },
    onLoad(options) {
      this.data.cardnum = options.num
      this.setData({
        cardnum: this.data.cardnum
      })
    },
    onShow() {
      app.memberReadyCb = () => {
      }
      app.fansReadyCb = () => {
        // app.checkMember()
        this.data.openid = app.globalData.fans.AppOpenID
        this.totalQuery()
      }
      app.init()
    },
    onShareAppMessage() {
      return app.shareInfo
    }
  }
})